<?php
namespace Custom\ExamBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Topxia\Common\ArrayToolkit;
use Topxia\Common\Paginator;
use Topxia\WebBundle\Controller\CourseQuestionManageController;
use Topxia\Service\Question\QuestionService;
use Symfony\Component\HttpFoundation\Response;
use Topxia\WebBundle\Controller\BaseController;
use Custom\Common\ExamEnum;

class CourseQuestionManageExtController extends CourseQuestionManageController
{
	public function indexAction(Request $request, $courseId)
	{echo 'sssssssssssss';  die;
		$course = $this->getCourseService()->tryManageCourse($courseId);
	
		$conditions = $request->query->all();

		if (!empty($conditions['target'])) {
			$conditions['targetPrefix'] = $conditions['target'];
		}
	
		if (!empty($conditions['keyword'])) {
			$conditions['stem'] = $conditions['keyword'];
		}
	
		if (!empty($conditions['parentId'])) {
	
			$parentQuestion = $this->getQuestionService()->getQuestion($conditions['parentId']);
			if (empty($parentQuestion)){
				return $this->redirect($this->generateUrl('course_manage_question',array('courseId' => $courseId)));
			}
	
			$orderBy = array('createdTime' ,'ASC');
		} else {
			$conditions['parentId'] = 0;
			$parentQuestion = null;
			$orderBy = array('createdTime' ,'DESC');
		}
	
		$paginator = new Paginator(
				$this->get('request'),
				$this->getQuestionExtService()->searchQuestionsCount($conditions),
				10
		);
	
		$questions = $this->getQuestionExtService()->searchQuestions(
				$conditions,
				$orderBy,
				$paginator->getOffsetCount(),
				$paginator->getPerPageCount()
		);
	
		$users = $this->getUserService()->findUsersByIds(ArrayToolkit::column($questions, 'userId'));

        $grades = ExamEnum::getGrades();
        $subjects = ExamEnum::getSubjects();

		return $this->render('TopxiaWebBundle:CourseQuestionManage:index.html.twig', array(
				'course' => $course,
				'questions' => $questions,
				'users' => $users,
				'paginator' => $paginator,
				'parentQuestion' => $parentQuestion,
				'conditions' => $conditions,
				'targetChoices'=> $this->getCategoryes(),
				'targets' => $this->getTargets(),
                'grades'=>$grades,
                'subjects'=>$subjects,
		));
	}
	
	public function createAction(Request $request, $courseId, $type)
	{
        $course = $this->getCourseService()->tryManageCourse($courseId);

        if ($request->getMethod() == 'POST') {
            $data = $request->request->all();

            $question = $this->getQuestionService()->createQuestion($data);

            if ($data['submission'] == 'continue') {
                $urlParams = ArrayToolkit::parts($question, array('target', 'difficulty', 'parentId'));
                $urlParams['type'] = $type;
                $urlParams['courseId'] = $courseId;
                $urlParams['goto'] = $request->query->get('goto', null);
                $this->setFlashMessage('success', '题目添加成功，请继续添加。');
                return $this->redirect($this->generateUrl('course_manage_question_create', $urlParams));
            } elseif ($data['submission'] == 'continue_sub') {
                $this->setFlashMessage('success', '题目添加成功，请继续添加子题。');
                return $this->redirect($request->query->get('goto', $this->generateUrl('course_manage_question', array('courseId' => $courseId, 'parentId' => $question['id']))));
            } else {
                $this->setFlashMessage('success', '题目添加成功。');
                return $this->redirect($request->query->get('goto', $this->generateUrl('course_manage_question', array('courseId' => $courseId))));
            }
        }

        $question = array(
            'id' => 0,
            'type' => $type,
            'target' => $request->query->get('target'),
            'difficulty' => $request->query->get('difficulty', 'normal'),
            'parentId' => $request->query->get('parentId', 0),
        );

        if ($question['parentId'] > 0) {
            $parentQuestion = $this->getQuestionService()->getQuestion($question['parentId']);
            if (empty($parentQuestion)){
                return $this->createMessageResponse('error', '父题不存在，不能创建子题！');
            }
        } else {
            $parentQuestion = null;
        }

        if ($this->container->hasParameter('enabled_features')) {
            $features = $this->container->getParameter('enabled_features');
        } else {
            $features = array();
        }

        $enabledAudioQuestion = in_array('audio_question', $features);

        $grades = ExamEnum::getGrades();
        $subjects = ExamEnum::getSubjects();

        return $this->render("TopxiaWebBundle:CourseQuestionManage:question-form-{$type}.html.twig", array(
            'course' => $course,
            'question' => $question,
            'parentQuestion' => $parentQuestion,
            'targetsChoices' => $this->getCreateCategoryes(),
            'categoryChoices' => $this->getQuestionCategoryChoices($course),
            'grades'=>$grades,
            'subjects'=>$subjects,
            'enabledAudioQuestion' => $enabledAudioQuestion
        ));
	}
	
	public function updateAction(Request $request, $courseId, $id)
	{
        $course = $this->getCourseService()->tryManageCourse($courseId);

        if ($request->getMethod() == 'POST') {
            $question = $request->request->all();

            $question = $this->getQuestionService()->updateQuestion($id, $question);

            $this->setFlashMessage('success', '题目修改成功！');

            return $this->redirect($request->query->get('goto', $this->generateUrl('course_manage_question',array('courseId' => $courseId,'parentId' => $question['parentId']))));
        }

        $question = $this->getQuestionService()->getQuestion($id);
        if ($question['parentId'] > 0) {
            $parentQuestion = $this->getQuestionService()->getQuestion($question['parentId']);
        } else {
            $parentQuestion = null;
        }
        
        if ($this->container->hasParameter('enabled_features')) {
        	$features = $this->container->getParameter('enabled_features');
        } else {
        	$features = array();
        }
        
        $enabledAudioQuestion = in_array('audio_question', $features);

        $grades = ExamEnum::getGrades();
        $subjects = ExamEnum::getSubjects();

        return $this->render("TopxiaWebBundle:CourseQuestionManage:question-form-{$question['type']}.html.twig", array(
            'course' => $course,
            'question' => $question,
            'parentQuestion' => $parentQuestion,
            'targetsChoices' =>  $this->getCreateCategoryes(),
            'categoryChoices' => $this->getQuestionCategoryChoices($course),
            'grades'=>$grades,
            'subjects'=>$subjects,
        	'enabledAudioQuestion' => $enabledAudioQuestion
            ));
	}
	
	public function paperQuestionPreviewAction($id)
	{
		$question = $this->getQuestionService()->getQuestion($id);
	
		if (empty($question)) {
			throw $this->createNotFoundException('题目不存在！');
		}
	
		$item = array(
				'questionId' => $question['id'],
				'questionType' => $question['type'],
				'question' => $question
		);
	
		if ($question['subCount'] > 0) {
			$questions = $this->getQuestionService()->findQuestionsByParentId($id);
	
			foreach ($questions as $value) {
				$items[] = array(
						'questionId' => $value['id'],
						'questionType' => $value['type'],
						'question' => $value
				);
			}
	
			$item['items'] = $items;
		}
	
		$type = in_array($question['type'], array('single_choice', 'uncertain_choice')) ? 'choice' : $question['type'];
		$questionPreview = true;
	
        return $this->render('CustomExamBundle:CourseQuestionManage:question-preview.html.twig', array(
                'item' => $item,
                'type' => $type,
                'questionPreview' => $questionPreview
        ));
	}
	
	private function getTargets()
	{
		$categories = $this->getCategoryService()->getCategoryTree(1);
		$choices = array();
		foreach ($categories as $category) {
			$categoryName = array("simple_name"=>$category['name']);
			$choices["category-".$category['id']] = $categoryName;
		}
		return $choices;
	}

    private function getCategoryes()
    {
        $categories = $this->getCategoryService()->getCategoryTree(1);
        $choices = array();
        foreach ($categories as $category) {
            $categoryName = $category['name'];
            for ($i = 2; $i <= $category["depth"]; $i++)
            {
                $categoryName = "&nbsp;&nbsp;&nbsp;". $categoryName;
            }
            $choices["category-".$category['id']] = $categoryName;
        }
        return $choices;
    }

	private function getCreateCategoryes()
	{
        $categories = $this->getCategoryService()->getCategoryTree(1);
        $tree = array();
        $this->create_tree($tree,$categories,0,"");
        return $tree;
	}

    private function create_tree(&$tree,&$categories,$parentId,$parentCode) {
        foreach ($categories as $category) {
            if ($category['parentId'] == $parentId) {
                $category['parentCode'] = empty($parentCode) ? "category-".$category["id"] :  $parentCode."/"."category-".$category["id"];

                $categoryName = $category['name'];
                for ($i = 2; $i <= $category["depth"]; $i++)
                {
                    $categoryName = "&nbsp;&nbsp;&nbsp;". $categoryName;
                }
                $tree[$category['parentCode']] = $categoryName;
                $this->create_tree($tree,$categories,$category["id"],$category['parentCode']);
            }
        }
        return $tree;
    }
	
	private function getQuestionCategoryChoices($course)
	{
		$categories = $this->getQuestionService()->findCategoriesByTarget("course-{$course['id']}", 0, QuestionService::MAX_CATEGORY_QUERY_COUNT);
		$choices = array();
		foreach ($categories as $category) {
			$choices[$category['id']] = $category['name'];
		}
		return $choices;
	}
	
	private function getCategoryService()
	{
		return $this->getServiceKernel()->createService('Taxonomy.CategoryService');
	}
	
	private function getCourseService()
	{
		return $this->getServiceKernel()->createService('Course.CourseService');
	}
	
	private function getQuestionService()
	{
		return $this->getServiceKernel()->createService('Question.QuestionService');
	}

    private function getQuestionExtService()
    {
        return $this->getServiceKernel()->createService('Custom:Question.QuestionService');
    }
}